package com.chocho.consumeserver.controller;

import com.chocho.consumeserver.service.GetwayService;
import com.chocho.consumeserver.utils.Msg;
import com.chocho.consumeserver.utils.SocketManager;
import com.chocho.consumeserver.vo.Code;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.websocket.EncodeException;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;

/**
 * Created by chocho on 2022/3/12.
 */
@RestController
@RequestMapping("/common")
public class CommonController {
    @Autowired
    private GetwayService getwayService;

    private Logger logger = LoggerFactory.getLogger(CommonController.class);

    @PostMapping("/compile")
    @ResponseBody
    public Map<String, Object> compile(@RequestBody Code code) {
        Map<String, Object> map = getwayService.inputQuestionCompile(code);
        return map;
    }

    @PostMapping("/pushResult")
    public void pushResult(@RequestBody Map<String, Object> map){

        String id = (String)map.get("questionId");
        logger.info("id:" + id);
        Session session = SocketManager.getInstance().getSessionMap().get(id);
        Msg msg = "200".equals(map.get("code")) ?
                Msg.success().add("res", map.get("res")) :
                Msg.fail().add("msg", map.get("msg")).add("detailMsg", map.get("detailMsg"));

        if(session == null){
            logger.info("session空");
            logger.error("push error!! session is null!, id: "+id+" score: "+ msg.toString());
            return;
        }
        logger.info("session不空");
        try {
            synchronized (session) {
                session.getBasicRemote().sendObject(msg);
            }
        } catch (IOException | EncodeException e) {
            logger.error("push error! id: "+id+" score: "+ msg.toString());
            //重试
            try {
                session.getBasicRemote().sendObject(msg);
            } catch (IOException | EncodeException e1) {
                logger.error("push retry error! id: "+id+" score: "+" score: "+ msg.toString(),e);
            }
            logger.error("push retry successful! id: "+id+" score: "+" score: "+ msg.toString());
        }
    }
}
